package com.doctor.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.doctor.entity.Case;
import com.doctor.exception.ServiceException;
import com.doctor.repository.CaseRepository;
import com.doctor.service.CaseService;

@Service
@Transactional
public class CaseServiceImpl implements CaseService {

@Resource
    private CaseRepository caseRepository;
    
    @Override
    public Page<Case> findAll(PageRequest pageRequest) {
        return caseRepository.findAll(pageRequest);
    }

    @Override
    public Case findById(Long id) {
        return caseRepository.findOne(id);
    }

    @Override
    public void delete(Long id) {
        caseRepository.delete(id);
    }

    @Override
    @Cacheable(value="case")
    public List<Case> findAllMan() {
        return caseRepository.findAll();
    }

	@Override
	public void saveOrUpdate(Case tbcase) {
        if(tbcase == null){
            throw new ServiceException("医师不能为空");
        }
        tbcase.setCreateTime(this.getCurrentDate());
        caseRepository.saveAndFlush(tbcase);
	}
    
    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

	@Override
	@Cacheable(value="case", key="#typeId")
	public List<Case> findByTypeIdOrderByCreateTimeDesc(int typeId) {
		return caseRepository.findByTypeIdOrderByCreateTimeDesc(typeId);
	}

}
